package com.cos.hospital.ui.patient;

import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.cos.hospital.R;
import com.cos.hospital.code.Code;
import com.cos.hospital.init.BaseActivity;
import com.cos.hospital.model.UHttp;
import com.cos.hospital.model.bean.ErrorBean;
import com.cos.hospital.model.bean.PatientInfo;
import com.cos.hospital.model.bean.PatientInfoBean;
import com.cos.hospital.model.bean.ResultBean;
import com.cos.hospital.model.connector.HttpMsgListener;
import com.cos.hospital.model.event.PatientInfoEditEvent;
import com.cos.hospital.tool.SPUtil;
import com.cos.hospital.tool.UDate;
import com.cos.hospital.tool.UKeyboard;
import com.cos.hospital.tool.URegular;
import com.cos.hospital.tool.USnackbar;
import com.cos.hospital.tool.UToast;
import com.cos.hospital.tool.UTxt;
import com.cos.hospital.ui.record.RecordEditActivity;
import com.cos.hospital.widget.ProgressDialog;
import com.google.gson.JsonObject;
import com.jude.utils.JTimeTransform;

import org.greenrobot.eventbus.EventBus;

import java.util.Calendar;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;

/**
 * 修改患者信息/患者建档
 */
public class PatientEditActivity extends BaseActivity {
    @BindView(R.id.tv_title_phone)
    TextView tv_title_phone;
    @BindView(R.id.edt_phone)
    EditText edt_phone;
    @BindView(R.id.tv_title_medical_num)
    TextView tv_title_medical_num;
    @BindView(R.id.edt_medical_num)
    EditText edt_medical_num;
    @BindView(R.id.tv_title_name)
    TextView tv_title_name;
    @BindView(R.id.edt_name)
    EditText edt_name;
    @BindView(R.id.rg)
    RadioGroup rg;
    @BindView(R.id.rb_man)
    RadioButton rb_man;
    @BindView(R.id.rb_woman)
    RadioButton rb_woman;
    @BindView(R.id.tv_birthday)
    TextView tv_birthday;
    @BindView(R.id.tv_age)
    TextView tv_age;
    @BindView(R.id.tv_title_idcard)
    TextView tv_title_idcard;
    @BindView(R.id.edt_idcard)
    EditText edt_idcard;
    @BindView(R.id.tv_title_address)
    TextView tv_title_address;
    @BindView(R.id.edt_address)
    EditText edt_address;
    @BindView(R.id.tv_reception)
    TextView tv_reception;
    private Calendar selectedDate;
    private UKeyboard keyboard;
    private int patientId;
    private PatientInfo patientInfo;

    @Override
    protected int layout() {
        return R.layout.activity_patient_edit;
    }

    @Override
    protected void init() {
        patientInfo = (PatientInfo) getIntent().getSerializableExtra(Code.SP.KEY);
        setTitleLeftIcon();
        selectedDate = Calendar.getInstance();
        keyboard = UKeyboard.with(this);
        if (patientInfo != null) {
            setTitleCenterTxt("修改患者信息");
            tv_reception.setText("保存");
            patientId = patientInfo.getFldPatientId();
            edt_phone.setText(patientInfo.getFldPhone());
            edt_medical_num.setText(patientInfo.getFldMedicalNum());
            edt_name.setText(patientInfo.getFldName());
            int fldSex = patientInfo.getFldSex();
            if (fldSex == 0) {
                rb_woman.setChecked(true);
            } else {
                rb_man.setChecked(true);
            }
            String fldBirthday = patientInfo.getFldBirthday();
            selectedDate = UDate.strToCalendar(fldBirthday);
            tv_birthday.setText(UDate.strToStrSafety(fldBirthday, "yyyy-MM-dd"));
            tv_age.setText(patientInfo.getFldAge() + "");
            edt_idcard.setText(patientInfo.getFldIdCardNo());
            edt_address.setText(patientInfo.getFldAddress());
        } else {
            setTitleCenterTxt("患者建档");
            tv_reception.setText("建档接诊");
            selectedDate.set(1991, 9, 1);
        }
        edt_phone.setFocusable(true);//可聚焦
        edt_phone.requestFocus();//聚焦
        edt_phone.setSelection(edt_phone.getText().length());//光标末尾
    }

    @Override
    protected void logic() {
        edt_phone.setOnFocusChangeListener((view, b) -> {
            if (!b) {
                checkPhone();
            }
        });
        edt_medical_num.setOnFocusChangeListener((view, b) -> {
            if (!b) {
                checkMedicalNum();
            }
        });
        edt_name.setOnFocusChangeListener((view, b) -> {
            if (!b) {
                checkName();
            }
        });
        edt_idcard.setOnFocusChangeListener((view, b) -> {
            if (!b) {
                checkIdcard();
            }
        });
        edt_address.setOnFocusChangeListener((view, b) -> {
            if (!b) {
                checkAddress();
            }
        });
    }

    @OnClick({R.id.title_back, R.id.tv_birthday, R.id.tv_reception})
    public void click(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.tv_birthday:
                if (keyboard.isKeyboardShow()) {
                    keyboard.hideForce(edt_name);
                }
                Calendar startDate = Calendar.getInstance();
                startDate.set(1900, 0, 1);
                Calendar endDate = Calendar.getInstance();
                new TimePickerBuilder(this, (date, v) -> {
                    selectedDate.setTime(date);
                    JTimeTransform jTimeTransform = new JTimeTransform(date.getTime() / 1000);
                    String format = jTimeTransform.toString("yyyy-MM-dd");
                    tv_birthday.setText(format);
                    int age = UDate.getAge(date);
                    tv_age.setText(age + "");
                }).setType(new boolean[]{true, true, true, false, false, false})
                    .setDate(selectedDate)
                    .setRangDate(startDate, endDate)
                    .isCenterLabel(false)
                    .build()
                    .show();
                break;
            case R.id.tv_reception:
                String phone = edt_phone.getText() + "";
                String medical_num = edt_medical_num.getText() + "";
                String name = edt_name.getText() + "";
                int checkedRadioButtonId = rg.getCheckedRadioButtonId();
                String birthday = tv_birthday.getText() + "";
                String idcard = edt_idcard.getText() + "";
                String address = edt_address.getText() + "";
                if (phone.length() == 0) {
                    USnackbar.showError(this, getString(R.string.phone_number_enter));
                    return;
                }
                if (!URegular.checkPhoneNum(phone)) {
                    USnackbar.showError(this, getString(R.string.phone_number_error));
                    return;
                }
                if (medical_num.length() < 7) {
                    USnackbar.showError(this, getString(R.string.medical_num_min_7));
                    return;
                }
                if (name.length() < 2) {
                    USnackbar.showError(this, getString(R.string.name_min_4));
                    return;
                }
                if (!URegular.checkChineseLetter(name)) {
                    USnackbar.showError(this, getString(R.string.name_latter_about));
                    return;
                }
                if (checkedRadioButtonId == -1) {
                    USnackbar.showError(this, getString(R.string.gender_error));
                    return;
                }
                if (birthday.length() == 0) {
                    USnackbar.showError(this, getString(R.string.birthday_error));
                    return;
                }
                if (idcard.length() != 0 && !URegular.checkIdCard(idcard)) {
                    USnackbar.showError(this, getString(R.string.idcard_number_error));
                    return;
                }
                if (address.length() != 0 && address.length() < 6) {
                    USnackbar.showError(this, getString(R.string.address_min_6));
                    return;
                }
                int fldSex;
                if (checkedRadioButtonId == R.id.rb_man) {
                    fldSex = 1;
                } else {
                    fldSex = 0;
                }
                if (patientInfo != null) {
                    patientInfoEdit(medical_num, name, fldSex, birthday, idcard, phone, address);
                } else {
                    patientCreat(medical_num, name, fldSex, birthday, idcard, phone, address);
                }
                break;
        }
    }

    private void patientInfoEdit(String medical_num, String name, int fldSex, String birthday, String idcard, String phone, String
        address) {
        ProgressDialog.getInstance().startProgressDialog(this);
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("fldPatientId", patientId);
        jsonObject.addProperty("fldMedicalNum", medical_num);
        jsonObject.addProperty("fldName", name);
        jsonObject.addProperty("fldSex", fldSex);
        jsonObject.addProperty("fldBirthday", birthday);
        jsonObject.addProperty("fldPhone", phone);
        jsonObject.addProperty("fldAddress", address);
        jsonObject.addProperty("idCard", idcard);
        UHttp.start(getServes().patientInfoEdit(jsonObject), "修改患者信息", new HttpMsgListener<ResultBean>() {
            @Override
            public void onSubscribe(Disposable disposable) {
                addEvent(disposable);
            }

            @Override
            public void onError(String describe) {
                USnackbar.showWarning(context, describe);
            }

            @Override
            public void onFinish() {
                ProgressDialog.getInstance().stopProgressDialog();
            }

            @Override
            public void onSuccess(ResultBean dto) {
                if (dto.isSuccess()) {
                    UToast.toast("修改成功");
                    EventBus.getDefault().post(new PatientInfoEditEvent());
                    finish();
                } else {
                    ErrorBean errorBean = dto.getError();
                    if (errorBean != null) {
                        showNotice(UTxt.isNull(errorBean.getMessage(), Code.DefaultPrompt));
                    } else {
                        showNotice(Code.DefaultPrompt);
                    }
                }
            }
        });
    }

    private void patientCreat(String medical_num, String name, int fldSex, String birthday, String idcard, String phone, String address) {
        ProgressDialog.getInstance().startProgressDialog(this);
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("fldMedicalNum", medical_num);
        jsonObject.addProperty("fldName", name);
        jsonObject.addProperty("fldSex", fldSex);
        jsonObject.addProperty("fldBirthday", birthday);
        jsonObject.addProperty("fldPhone", phone);
        jsonObject.addProperty("fldAddress", address);
        jsonObject.addProperty("fldDoctorId", SPUtil.getUserId());
        jsonObject.addProperty("fldIDCardNo", idcard);
        UHttp.start(getServes().patientCreat(jsonObject), "患者建档", new HttpMsgListener<ResultBean<Integer>>() {
            @Override
            public void onSubscribe(Disposable disposable) {
                addEvent(disposable);
            }

            @Override
            public void onError(String describe) {
                ProgressDialog.getInstance().stopProgressDialog();
                USnackbar.showWarning(context, describe);
            }

            @Override
            public void onSuccess(ResultBean<Integer> dto) {
                if (dto.isSuccess()) {
                    reception(dto.getResult());
                } else {
                    ProgressDialog.getInstance().stopProgressDialog();
                    ErrorBean errorBean = dto.getError();
                    if (errorBean != null) {
                        showNotice(UTxt.isNull(errorBean.getMessage(), Code.DefaultPrompt));
                    } else {
                        showNotice(Code.DefaultPrompt);
                    }
                }
            }
        });
    }

    private void reception(int fldPatientId) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("fldPatientId", fldPatientId);
        jsonObject.addProperty("fldDoctorId", SPUtil.getUserId());
        jsonObject.addProperty("fldEditId", SPUtil.getUserId());
        jsonObject.addProperty("fldMedicalFlag", 0);//初复诊标识 初诊 = 0,复诊 = 1
        UHttp.start(getServes().saveMedical(jsonObject), "病历保存(可同时签到接诊)", new HttpMsgListener<ResultBean<Integer>>() {
            @Override
            public void onSubscribe(Disposable disposable) {
                addEvent(disposable);
            }

            @Override
            public void onError(String describe) {
                USnackbar.showWarning(context, describe);
            }

            @Override
            public void onFinish() {
                ProgressDialog.getInstance().stopProgressDialog();
            }

            @Override
            public void onSuccess(ResultBean<Integer> dto) {
                if (dto.isSuccess()) {
                    Intent intent = new Intent(context, RecordEditActivity.class);
                    intent.putExtra(Code.SP.ID, dto.getResult());
                    startActivity(intent);
                    finish();
                    sendBroadcast(new Intent(Code.Broadcast.CutoverToReception));
                } else {
                    ErrorBean errorBean = dto.getError();
                    if (errorBean != null) {
                        showNotice(UTxt.isNull(errorBean.getMessage(), Code.DefaultPrompt));
                    } else {
                        showNotice(Code.DefaultPrompt);
                    }
                }
            }
        });
    }

    private void checkPhone() {
        String phone = edt_phone.getText() + "";
        if (phone.length() == 0) {
            changeUI(tv_title_phone, edt_phone, R.color.red_default, R.drawable.shape_input_red);
            return;
        }
        if (!URegular.checkPhoneNum(phone)) {
            changeUI(tv_title_phone, edt_phone, R.color.red_default, R.drawable.shape_input_red);
            return;
        }
        changeUI(tv_title_phone, edt_phone, R.color.black_txt, R.color.white);
    }

    private void checkMedicalNum() {
        String medical_num = edt_medical_num.getText() + "";
        if (medical_num.length() < 7) {
            changeUI(tv_title_medical_num, edt_medical_num, R.color.red_default, R.drawable.shape_input_red);
            return;
        }
        changeUI(tv_title_medical_num, edt_medical_num, R.color.black_txt, R.color.white);
    }

    private void checkName() {
        String name = edt_name.getText() + "";
        if (name.length() < 2) {
            changeUI(tv_title_name, edt_name, R.color.red_default, R.drawable.shape_input_red);
            return;
        }
        if (!URegular.checkChineseLetter(name)) {
            changeUI(tv_title_name, edt_name, R.color.red_default, R.drawable.shape_input_red);
            return;
        }
        changeUI(tv_title_name, edt_name, R.color.black_txt, R.color.white);
    }

    private void checkIdcard() {
        String idcard = edt_idcard.getText() + "";
        if (idcard.length() != 0 && !URegular.checkIdCard(idcard)) {
            changeUI(tv_title_idcard, edt_idcard, R.color.red_default, R.drawable.shape_input_red);
            return;
        }
        changeUI(tv_title_idcard, edt_idcard, R.color.black_txt, R.color.white);
    }

    private void checkAddress() {
        String address = edt_address.getText() + "";
        if (address.length() != 0 && address.length() < 6) {
            changeUI(tv_title_address, edt_address, R.color.red_default, R.drawable.shape_input_red);
            return;
        }
        changeUI(tv_title_address, edt_address, R.color.black_txt, R.color.white);
    }

    private void changeUI(TextView tv, TextView edt, int textColorRes, int edtBgRes) {
        tv.setTextColor(ContextCompat.getColor(this, textColorRes));
        edt.setBackgroundResource(edtBgRes);
    }

}
